package api

import (
	"bishow/modbus"
	"encoding/json"
	"html/template"
	"net/http"
)

var servers []*modbus.ModbusServer

func init() {
	servers = append(servers, modbus.NewModbusServer())
}

func StartModbusServer(w http.ResponseWriter, r *http.Request) {
	for i := 0; i < len(servers); i++ {
		servers[i].Start()
	}
	json.NewEncoder(w).Encode(map[string]string{"status": "started"})
}

func StopModbusServer(w http.ResponseWriter, r *http.Request) {
	for i := 0; i < len(servers); i++ {
		servers[i].Stop()
	}
	json.NewEncoder(w).Encode(map[string]string{"status": "stopped"})
}

func CreateModbusServer(w http.ResponseWriter, r *http.Request) {
	servers = append(servers, modbus.NewModbusServer())
	json.NewEncoder(w).Encode(map[string]string{"status": "created"})
}

func PauseModbusServer(w http.ResponseWriter, r *http.Request) {
	for i := 0; i < len(servers); i++ {
		servers[i].Pause()
	}
	json.NewEncoder(w).Encode(map[string]string{"status": "paused"})
}

func ResumeModbusServer(w http.ResponseWriter, r *http.Request) {
	for i := 0; i < len(servers); i++ {
		servers[i].Resume()
	}
	json.NewEncoder(w).Encode(map[string]string{"status": "resumed"})
}

func GetModbusData(w http.ResponseWriter, r *http.Request) {
	data := servers[0].GetData()
	json.NewEncoder(w).Encode(data)
}

func ServeHTML(w http.ResponseWriter, r *http.Request) {
	tmpl := template.Must(template.New("index.html").Delims("{-[", "]-}").ParseFiles("templates/index.html"))
	tmpl.Execute(w, nil)
}
